package wnhz.com.business.groupshop.ui;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.shareshop.bean.CompleteInfoBean;
import wnhz.com.business.uitls.ImageLoaderUtil;
import wnhz.com.business.uitls.MyBitmapUtils;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.view.CircleImageView;
import wnhz.com.business.view.TranslucentActionBar;

import static com.umeng.socialize.utils.ContextUtil.getContext;
/**
 * 修改个人信息
 */
public class MeassageChangeActivity extends BaseActivity implements View.OnClickListener, ActionBarClickListener {

    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.ll_touxiang)
    LinearLayout ll_touxiang;
    @BindView(R.id.et_nick)
    EditText et_nick;
    @BindView(R.id.sex_man)
    RadioButton sex_man;
    @BindView(R.id.sex_woman)
    RadioButton sex_woman;
    @BindView(R.id.et_date)
    EditText et_date;
    @BindView(R.id.img_head)
    CircleImageView img_head;


    private TextView tv_takepoto, tv_choosephoto, tv_cancel,empty_takepic;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private PopupWindow popup;
    private final int TAKE_PHOTO = 1;
    private final int CHOOSE_PHOTO = 2;
    private File output;
    private Uri imageUri;
    private Bitmap bm = null;

    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, MeassageChangeActivity.class);
        return intent;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meassage_change);
        ButterKnife.bind(this);

        actionbar.setData("信息修改", R.drawable.ic_lefft_white, null, 0, "跳过", 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }

        makeflie();
        loadData();
    }
    /**
     * 获取个人信息
     */
    private void loadData() {
        Map<String,String> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        map.put("token",MyApplication.getInstance().getInfoBean().getToken());
        OkGo.<String>post(Url.UCENTER_INFO)
                .tag(this)
                .params(map,false)
                .execute(new DialogCallback<String>(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("个人中心修改信息", response.body().toString());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().toString());
                            String re = jsonObject.optString("re");
                            if (re.equals("1")){
                                Gson gson = new Gson();
                                CompleteInfoBean meassageChangeBean = gson.fromJson(response.body().toString(), CompleteInfoBean.class);
                                et_nick.setText(meassageChangeBean.getInfo().getUsername() == null ? "" : meassageChangeBean.getInfo().getUsername());//
                                if(!TextUtils.isEmpty(meassageChangeBean.getInfo().getHead_img())){
                                    ImageLoaderUtil.displayImage(getContext(),img_head,meassageChangeBean.getInfo().getHead_img(),null);//
                                }

                                if("1".equals(meassageChangeBean.getInfo().getSex())){
                                    sex_man.setChecked(true);
                                    sex_woman.setChecked(false);
                                }else if("2".equals(meassageChangeBean.getInfo().getSex())){
                                    sex_man.setChecked(false);
                                    sex_woman.setChecked(true);
                                }
                                et_date.setText(meassageChangeBean.getInfo().getBirth() == null ? "" : meassageChangeBean.getInfo().getBirth());
                            }else {
                                ToastUtils.showToast(MeassageChangeActivity.this,"获取信息失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("个人中心onError","------------");
                    }
                });
    }


    @OnClick({R.id.ll_touxiang})
    public void onViewClicked(View v) {
        switch (v.getId()){
            case R.id.ll_touxiang:
                seepop();
                break;
        }
    }

    private void seepop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.item_takephoto, null);
        popup = new PopupWindow(contentView);
        popup.setOutsideTouchable(true);
        popup.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popup.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popup.showAsDropDown(actionbar, 0, 0);
        tv_takepoto = (TextView) contentView.findViewById(R.id.tv_takepoto);
        tv_choosephoto = (TextView) contentView.findViewById(R.id.tv_choosepoto);
        tv_cancel = (TextView) contentView.findViewById(R.id.tv_cancel);
        empty_takepic = (TextView) contentView.findViewById(R.id.empty_takepic);
        tv_takepoto.setOnClickListener(this);
        tv_choosephoto.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        empty_takepic.setOnClickListener(this);
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
        MyToast("保存成功");
        MeassageChangeUpData();
    }

    private void MeassageChangeUpData() {

    }

    @Override
    public void onEditTextClick() {

    }


    private void makeflie() {
        /**
         * 最后一个参数是文件夹的名称，可以随便起
         */
        String path = Environment.getExternalStorageDirectory().toString() + "/SYB";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        /**
         * 这里将时间作为不同照片的名称
         */
        output = new File(file, System.currentTimeMillis() + ".jpg");

        /**
         * 如果该文件夹已经存在，则删除它，否则创建一个
         */
        try {
            if (output.exists()) {
                output.delete();
            }
            output.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //拍照
            case R.id.tv_takepoto:

                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA}, 3);

                } else {
                    imageUri = Uri.fromFile(output);
                    Intent intents = new Intent("android.media.action.IMAGE_CAPTURE");
                    intents.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intents, TAKE_PHOTO);
                    popup.dismiss();
                }

                break;
            //选择相册
            case R.id.tv_choosepoto:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");//相片类型
                startActivityForResult(intent, CHOOSE_PHOTO);
                popup.dismiss();
                break;
            //取消
            case R.id.tv_cancel:
                popup.dismiss();
                break;
            case R.id.empty_takepic:
                popup.dismiss();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case TAKE_PHOTO:
                    try {
                        img_head.setImageBitmap(MyBitmapUtils.getSmallBitmap(output.getPath()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case CHOOSE_PHOTO:
                    ContentResolver resolver = getContentResolver();
                    try {
                        Uri originalUri = data.getData();   //获得图片的uri
                        bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                        String[] proj = {MediaStore.Images.Media.DATA};//显得到bitmap图片
                        Cursor cursor = managedQuery(originalUri, proj, null, null, null);//用过游标来获取本地相册中的路径
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        cursor.moveToFirst();//将游标移到开头，防止越界
                        String path = cursor.getString(column_index);
                        img_head.setImageBitmap(MyBitmapUtils.getSmallBitmap(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }
}
